<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Achievement;
use addons\qingdong\model\Achievement as AchievementModel;
use addons\qingdong\model\ContractRatio;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Leads;
use addons\qingdong\model\Customer;
use addons\qingdong\model\ReceivablesPlan;
use addons\qingdong\model\Record;
use addons\qingdong\model\Staff;


/**
 * 统计接口
 */
class Statistics extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	/**
	 *成交排行
	 */
	public function contractRanding() {
//		$date = input('date', date('Y-m'));
		$type = input('type', 0);//0 本人及下属 1 仅本人 2 仅下属 3公司
        $status=input('status',1);//1 合同 2 回款
        $times=input('times','');
        $times=explode(',',$times);
        if(empty($times)){
            $this->error('参数不能为空');
        }
        $startDate=date("Y-m",strtotime($times[0]));
        $endDate=date("Y-m",strtotime($times[1]));
		$between=[$times[0],$times[1]];
        if($status == 1){
            $contracts = Contract::where([
                'order_date'   => ['between', $between],
                'check_status' => 2,
            ])->group('owner_staff_id')->field('owner_staff_id,sum(money) as money')->order('money desc')->select();
            $list      = [];
            foreach ($contracts as $v) {
                $list[$v['owner_staff_id']] = $v['money'];
            }
        }else{
            $receivables = Receivables::where([
                'return_time'   => ['between', $between],
                'check_status' => 2,
            ])->group('owner_staff_id')->field('owner_staff_id,sum(money) as money')->order('money desc')->select();
            $list      = [];
            foreach ($receivables as $v) {
                $list[$v['owner_staff_id']] = $v['money'];
            }
        }

		$data      = [];
		$staffs    = Staff::getList();
		foreach ($staffs as $v) {
			if (isset($list[$v['id']])) {
				$data[$v['id']] = $list[$v['id']];
			} else {
				$data[$v['id']] = 0;
			}
		}
		arsort($data);
		$staffs   = Staff::getKeyList();
		$result   = [];
		$i        = 1;
		$oneMoney = 0;
		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
		} elseif ($type == 3) {//公司
			$showStaffIds = Staff::getLowerStaffId();
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
		}


		foreach ($data as $id => $money) {
			if ($i == 1) {
				$oneMoney = $money;
			}
			$val          = $staffs[$id];
			$val['money'] = $money;
			$val['ratio'] = ($money && $oneMoney) ? sprintf("%.2f", $money / $oneMoney * 100) : 0;
			$val['rank']  = $i;
			$i++;
			if(in_array($id,$showStaffIds)){
				$result[]     = $val;
			}
		}

		if (count($result) >= 10) {
			$top    = array_slice($result, 0, 3);
			$bottom = array_slice($result, -3, 3);
			$middle = array_slice($result, 3, 4);
			$result = array_merge($top, $bottom, $middle);
		}

		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
			//业绩目标完成情况
            $data = Achievement::getStaffAchievement($startDate,$endDate,$status);
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
			//业绩目标完成情况
            $data = Achievement::getStaffAchievement($startDate,$endDate,$status);
		} elseif ($type == 3) {//公司
			$showStaffIds = Staff::getLowerStaffId();
			//业绩目标完成情况
			$data = Achievement::getCompanyAchievement($startDate,$endDate,$status);
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
			//业绩目标完成情况
            $data = Achievement::getStaffAchievement($startDate,$endDate,$status);
		}

        $achievement=$data['achievement']??0;
        if($status == 1){
            $totalMoneys = Contract::where([
                'order_date'     => ['between', $between],
                'check_status'   => 2,
                'owner_staff_id' => ['in',$showStaffIds],
            ])->sum('money');
        }else{
            $totalMoneys = Receivables::where([
                'return_time'     => ['between', $between],
                'check_status'   => 2,
                'owner_staff_id' => ['in',$showStaffIds],
            ])->sum('money');
        }

        $ratio = ($totalMoneys && intval($achievement)) ? (intval($achievement) == 0) ? 100 : round($totalMoneys / $achievement * 100, 2) : 0;
		$data  = [
			'achievement'       => $achievement,
			'contract_moneys'   => $totalMoneys,
			'completion_status' => ($ratio >= 100) ? 1 : 0,//完成状态
			'ratio'             => $ratio,
			'ranking'           => $result
		];

		$this->success('请求成功', $data);
	}


    /**
     * 合同排行 机型排行
     */
	public function contractRanking() {

		$date = input('date', date('Y-m'));
		$type = input('type', 0);//0 本人及下属 1 仅本人 2 仅下属
		//月底
		$endDate = date('Y-m-d', strtotime('+1 month', strtotime($date . '-1')) - 1);

		$contracts = Contract::where([
			'order_date'   => ['between', [$date . '-1', $endDate]],
			'check_status' => 2,
		])->group('owner_staff_id')->field('owner_staff_id,count(*) as contract_number')->order('contract_number desc')->select();
		$list      = [];
		foreach ($contracts as $v) {
			$list[$v['owner_staff_id']] = $v['contract_number'];
		}
		$contracts = $list;

		$data   = [];
		$staffs = Staff::getList();
		foreach ($staffs as $v) {
			if (isset($contracts[$v['id']])) {
				$data[$v['id']] = $contracts[$v['id']];
			} else {
				$data[$v['id']] = 0;
			}
		}
		arsort($data);
		$staffs    = Staff::getKeyList();
		$result    = [];
		$i         = 1;
		$oneNumber = 0;
		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
		}
		foreach ($data as $id => $number) {
			if ($i == 1) {
				$oneNumber = $number;
			}
			$val           = $staffs[$id];
			$val['number'] = $number;
			$val['ratio']  = $oneNumber ? sprintf("%.2f", $number / $oneNumber * 100) : 0;
			$val['rank']   = $i;
			$i++;
			if(in_array($id,$showStaffIds)){
				$result[]     = $val;
			}
		}
		if (count($result) >= 10) {

			$top    = array_slice($result, 0, 3);
			$bottom = array_slice($result, -3, 3);
			$middle = array_slice($result, 3, 4);
			$result = array_merge($top, $bottom, $middle);
		}

		$this->success('请求成功', $result);
	}


    /**
     * 回款统计
     */
	public function receivablesStatistics() {
        $type = input('type',0); //0:全部 1：我负责的 2：下属负责的
        switch($type){
            case 1:
                $wheres['owner_staff_id'] =  $this->auth->id;
                break;
            case 2:
                $wheres['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                break;
            default:
                $wheres['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                break;

        }
		$contract_moneys    = Contract::where(['owner_staff_id' => $this->auth->id, 'check_status' => 2])->sum('money');
		$receivables_moneys = Receivables::where($wheres)->where([
			'check_status'   => 2,
		])->sum('money');
		$plan_moneys        = ReceivablesPlan::where($wheres)->where([
			'status'         => 0,
		])->sum('money');
		$no_moneys          = $contract_moneys - $receivables_moneys;
		$startDate          = date('Y-01');
		$endDate            = date('Y-m');

		$plans      = ReceivablesPlan::where($wheres)->group('dates')->field('sum(money) as money,FROM_UNIXTIME(UNIX_TIMESTAMP(return_date),"%Y-%m") as dates')->select();
		$plans_list = [];
		foreach ($plans as $item) {
			$plans_list[$item['dates']] = $item['money'];
		}
		$receivables      = Receivables::where($wheres)->group('dates')->field('sum(money) as money,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as dates')->select();
		$receivables_list = [];
		foreach ($receivables as $item) {
			$receivables_list[$item['dates']] = $item['money'];
		}
		$data = [];
		for ($startDate; strtotime($startDate) <= strtotime($endDate); $startDate = date('Y-m', strtotime($startDate . ' +1 month'))) {
			$row       = [
				'date'        => $startDate,
				'plan'        => $plans_list[$startDate] ?? 0,
				'receivables' => $receivables_list[$startDate] ?? 0,
			];
			$row['no'] = ($row['plan'] - $row['receivables']) > 0 ? $row['plan'] - $row['receivables'] : 0;
			$data[]    = $row;
		}

		$this->success('请求成功', [
			'contract_moneys'    => $contract_moneys,
			'receivables_moneys' => $receivables_moneys,
			'plan_moneys'        => $plan_moneys,
			'no_moneys'          => $no_moneys,
			'data'               => $data
		]);
	}

    /**
     * 所属员工回款统计
     */
	public function staffReceivablesStatistics() {
		$ids = Staff::getMyStaffIds();


		$contract_moneys    = Contract::where([
			'owner_staff_id' => ['in', $ids],
			'check_status'   => 2,
		])->sum('money');
		$receivables_moneys = Receivables::where([
			'owner_staff_id' => ['in', $ids],
			'check_status'   => 2,
		])->sum('money');
		$plan_moneys        = ReceivablesPlan::where([
			'owner_staff_id' => ['in', $ids],
			'status'         => 0,
		])->sum('money');
		$no_moneys          = $contract_moneys - $receivables_moneys;

		$contracts      = Contract::where([
			'owner_staff_id' => [
				'in',
				$ids
			],
			'check_status'   => 2,
		])->group('owner_staff_id')->field('sum(money) as money,owner_staff_id')->select();
		$contracts_list = [];
		foreach ($contracts as $item) {
			$contracts_list[$item['owner_staff_id']] = $item['money'];
		}

		$plans      = ReceivablesPlan::where([
			'owner_staff_id' => [
				'in',
				$ids
			],
			'status'         => 0,
		])->group('owner_staff_id')->field('sum(money) as money,owner_staff_id')->select();
		$plans_list = [];
		foreach ($plans as $item) {
			$plans_list[$item['owner_staff_id']] = $item['money'];
		}

		$receivables      = Receivables::where([
			'owner_staff_id' => [
				'in',
				$ids
			],
			'check_status'   => 2,
		])->group('owner_staff_id')->field('sum(money) as money,owner_staff_id')->select();
		$receivables_list = [];
		foreach ($receivables as $item) {
			$receivables_list[$item['owner_staff_id']] = $item['money'];
		}
		$data   = [];
		$ids    = Staff::getMyStaffIds();
		$staffs = Staff::where(['id' => ['in', $ids]])->field('id,name')->select();
		foreach ($staffs as $v) {
			$row       = [
				'id'          => $v['id'],
				'name'        => $v['name'],
				'contracts'        => $contracts_list[$v['id']] ?? 0,
				'plan'        => $plans_list[$v['id']] ?? 0,
				'receivables' => $receivables_list[$v['id']] ?? 0,
			];
			$row['no'] = ($row['contracts'] - $row['receivables']) > 0 ? $row['contracts'] - $row['receivables'] : 0;
			$data[]    = $row;
		}
		$this->success('请求成功', [
			'contract_moneys'    => $contract_moneys,
			'receivables_moneys' => $receivables_moneys,
			'plan_moneys'        => $plan_moneys,
			'no_moneys'          => $no_moneys,
			'data'               => $data
		]);
	}

    /**
     * 我的业绩目标完成度
     */
	public function staffAchievementStatistics() {
		$year = input('year', date('Y'));
		$type = input('type', 0);
		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
			$yearAchievement = Achievement::getStaffYearAchievement($year);
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
			$yearAchievement = Achievement::getTeamYearAchievement($year);
		} elseif ($type == 3) {//公司
			$showStaffIds = Staff::getLowerStaffId();
			$yearAchievement = Achievement::getCompanyYearAchievement($year);
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
			$yearAchievement = Achievement::getTeamYearAchievement($year);
		}
        $contracts=ContractRatio::where([
            'contract.check_status'=>2, 'contract_ratio.staff_id' => ['in',$showStaffIds],
            'contract.order_date'=>['like', $year . '%']
        ])->with(['contract'])->select();
        $contracts=collection($contracts)->toArray();
        $contractData=[];
        foreach ($contracts as $v) {
            $order_date = $v['contract']['order_date'];
            $month = date('Y-m', strtotime($order_date));
            $contractData[$month]['money'][] = $v['ratio_money'];
            $contractData[$month]['contract_id'][] = $v['contract_id'];
        }

        $contracts_list  = [];
        foreach ($contractData as $month=>$v) {
            $contracts_list[$month] = ['money'=>array_sum($v['money']),'count'=>count($v['contract_id'])];
        }

		$data = [];
		foreach ($yearAchievement as $k => $v) {
			if ($month = Achievement::getFieldMonth($k)) {
				$month             = $year . '-' . $month;
				$row               = [
					'month'       => $month,
					'achievement' => $v,
					'money'       => isset($contracts_list[$month]) ? $contracts_list[$month]['money'] : 0,
					'count'       => isset($contracts_list[$month]) ? $contracts_list[$month]['count'] : 0,
				];
				$row['ratio']      = ($row['money'] && intval($row['achievement'])) ? sprintf("%.2f", $row['money'] / $row['achievement'] * 100) : 0;
				$row['unit_price'] = ($row['money'] && $row['count']) ? sprintf("%.2f", $row['money'] / $row['count']) : 0;

				$data[] = $row;
			}
		}

		$this->success('请求成功', $data);
	}


    /**
     * 回款数据排行
     */
	public function receivablesRanking() {
		$year = input('year', date('Y'));
		$type = input('type', 0);
		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
		}

		$receivables = Receivables::where([
			'check_status' => 2,
			'return_time'  => ['like', $year . '%'],
		])->group('owner_staff_id')->with(['staff'])->order('money desc')->field('owner_staff_id,sum(money) as money,count(*) as count')->select();

		$receivablesData = [];
		$list            = [];
		$i=1;
		foreach ($receivables as $k => $v) {
			$v['ranking']               = $i;
			if(in_array($v['owner_staff_id'],$showStaffIds)){
                $i++;
				$receivablesData[]          = $v;
			}
			$list[$v['owner_staff_id']] = $v['money'];
		}

		$contracts = $list;

		$data   = [];
		$staffs = Staff::getList();
		foreach ($staffs as $v) {
			if (isset($contracts[$v['id']])) {
				$data[$v['id']] = $contracts[$v['id']];
			} else {
				$data[$v['id']] = 0;
			}
		}
		arsort($data);
		$staffs    = Staff::getKeyList();
		$result    = [];
		$i         = 1;
		$oneNumber = 0;
		foreach ($data as $id => $number) {
			if ($i == 1) {
				$oneNumber = $number;
			}
			$val           = $staffs[$id];
			$val['number'] = $number;
			$val['ratio']  = $oneNumber ? sprintf("%.2f", $number / $oneNumber * 100) : 0;
			$val['rank']   = $i;
			if(in_array($id,$showStaffIds)){
				$result[]     = $val;
                $i++;
			}
		}

		if (count($result) >= 10) {

			$top    = array_slice($result, 0, 3);
			$bottom = array_slice($result, -3, 3);
			$middle = array_slice($result, 3, 4);
			$result = array_merge($top, $bottom, $middle);
		}


		$this->success('请求成功', ['ranking' => $result, 'data' => $receivablesData]);
	}


    /**
     * 成交数据排行
     */
	public function contractMoneyRanking() {
		$date = input('year', date('Y'));
		$type = input('type', 0);
		if ($type == 1) {//本人
			$showStaffIds = [$this->auth->id];
		} elseif ($type == 2) {//下属
			$showStaffIds = Staff::getLowerStaffId();
		} else {//全部
			$showStaffIds = Staff::getMyStaffIds();
		}
        $contracts=ContractRatio::where([
            'contract.check_status'=>2, 'contract_ratio.staff_id' => ['in',$showStaffIds],
            'contract.order_date'=>['like', $date . '%']
        ])->with(['contract','staff'])->select();
        $contracts=collection($contracts)->toArray();
        $contractData=[];
        foreach ($contracts as $v) {
            $contractData[$v['staff_id']]['money'][] = $v['ratio_money'];
            $contractData[$v['staff_id']]['contract_id'][] = $v['contract_id'];
            $contractData[$v['staff_id']]['staff'] = $v['staff'];
            $contractData[$v['staff_id']]['staff_id'] = $v['staff_id'];
        }

        $receivables  = [];
        foreach ($contractData as $v) {
            $receivables[] = [
                'money'=>array_sum($v['money']),
                'count'=>count($v['contract_id']),
                'staff'=>$v['staff'],
                'owner_staff_id'=>$v['staff_id'],
            ];
        }
        $this->arraySortByOneField($receivables,'money',SORT_DESC);
		$receivablesData = [];
		$list            = [];
		foreach ($receivables as $k => $v) {
			$v['ranking']               = $k + 1;
			$v['unit_price']            = ($v['money'] && $v['count']) ? sprintf("%.2f", $v['money'] / $v['count']) : 0;
			if(in_array($v['owner_staff_id'],$showStaffIds)){
				$receivablesData[]          = $v;
			}
			$list[$v['owner_staff_id']] = $v['money'];
		}

		$contracts = $list;

		$data   = [];
		$staffs = Staff::getList();
		foreach ($staffs as $v) {
			if (isset($contracts[$v['id']])) {
				$data[$v['id']] = $contracts[$v['id']];
			} else {
				$data[$v['id']] = 0;
			}
		}
		arsort($data);
		$staffs    = Staff::getKeyList();
		$result    = [];
		$i         = 1;
		$oneNumber = 0;
		foreach ($data as $id => $number) {
			if ($i == 1) {
				$oneNumber = $number;
			}
			$val           = $staffs[$id];
			$val['number'] = $number;
			$val['ratio']  = $oneNumber ? sprintf("%.2f", $number / $oneNumber * 100) : 0;
			$val['rank']   = $i;
			$i++;
			if(in_array($id,$showStaffIds)){
				$result[]     = $val;
			}
		}

		if (count($result) >= 10) {

			$top    = array_slice($result, 0, 3);
			$bottom = array_slice($result, -3, 3);
			$middle = array_slice($result, 3, 4);
			$result = array_merge($top, $bottom, $middle);
		}


		$this->success('请求成功', ['ranking' => $result, 'data' => $receivablesData]);
	}

    /**
     * 新增排行
     */
	public function newRanking() {
		$year      = input('date', date('Y'));
		$between   = [strtotime($year . '-01-01'), strtotime($year.'-1-1 +1 year')];
        $betweenC   = [date('Y-m-d 00:00:00',strtotime($year . '-01-01')), date('Y-m-d 23:59:59',strtotime($year.'-1-1 +1 year'))];
		$customers = Customer::where([
			'createtime' => [
				'between',
				$between
			],
			'owner_staff_id' => $this->auth->id
		])->group('month')->field("FROM_UNIXTIME(createtime,'%Y-%m') as month,count(*) as count")->select();

		$customers_list = [];
		foreach ($customers as $v) {
			$customers_list[$v['month']] = $v['count'];
		}
		$contracts      = Contract::where([
			'order_date' => [
				'between',
                $betweenC
			],
			'owner_staff_id' => $this->auth->id,
            'check_status'=>2
		])->group('month')->field('FROM_UNIXTIME(createtime,"%Y-%m") as month,count(*) as count')->select();

		$contracts_list = [];
		foreach ($contracts as $v) {
			$contracts_list[$v['month']] = $v['count'];
		}
		$leads      = Leads::where([
			'createtime' => [
				'between',
				$between
			],
			'owner_staff_id' => $this->auth->id
		])->group('month')->field('FROM_UNIXTIME(createtime,"%Y-%m") as month,count(*) as count')->select();
		$leads_list = [];
		foreach ($leads as $v) {
			$leads_list[$v['month']] = $v['count'];
		}
		$data = [];
		for ($i = 1; $i <= 12; $i++) {
			$month  = date('Y-m', strtotime($year . '-' . $i));
			$data[] = [
				'month'     => $month,
				'customers' => $customers_list[$month] ?? 0,
				'contracts' => $contracts_list[$month] ?? 0,
				'leads'     => $leads_list[$month] ?? 0,
			];
		}

		$this->success('请求成功', $data);
	}

    /**
     * 获取团队新增统计
     */
	public function addCustomerStatistics() {
		$date = input('date', date('Y-m'));
		if(strlen($date) == 4){
			$between = [strtotime($date . '-01-01'), strtotime($date.'-1-1 +1 year') - 1];
		}else{
			$between = [strtotime($date), strtotime('+1 month', strtotime($date)) - 1];
		}


		$ids     = Staff::getMyStaffIds();
		$staffs  = Staff::where(['id' => ['in', $ids]])->field('id,name,post,img')->select();

		$c         = Customer::where([
			'createtime'      => [
				'between',
				$between
			],
			'owner_staff_id' => ['in', $ids]
		])->group('owner_staff_id')->order('count desc')->field("owner_staff_id,count(*) as count")->select();
		$customers = [];
		foreach ($c as $v) {
			$customers[$v['owner_staff_id']] = $v['count'];
		}
		$l     = Leads::where([
			'createtime'      => [
				'between',
				$between
			],
			'owner_staff_id' => ['in', $ids]
		])->group('owner_staff_id')->field("owner_staff_id,count(*) as count")->select();
		$leads = [];
		foreach ($l as $v) {
			$leads[$v['owner_staff_id']] = $v['count'];
		}
		$t         = Contract::where([
			'createtime'      => [
				'between',
				$between
			],
			'owner_staff_id' => ['in', $ids]
		])->group('owner_staff_id')->field("owner_staff_id,count(*) as count")->select();
		$contracts = [];
		foreach ($t as $v) {
			$contracts[$v['owner_staff_id']] = $v['count'];
		}
		$total=[];
		$total[0]=[
			'name'=>'数据汇总',
			'id'=>0,
			'leads'=>0,
			'customers'=>0,
			'contracts'=>0,
		];
		$sort=[];
		foreach ($staffs as $k => $v) {

			$v['leads']     = $leads[$v['id']] ?? 0;
			$v['customers'] = $customers[$v['id']] ?? 0;
			$v['contracts'] = $contracts[$v['id']] ?? 0;
			$sort[$v['id']] = $v['leads'] + $v['customers'] + $v['contracts'];
			$total[0]['leads'] += $v['leads'];
			$total[0]['customers'] += $v['customers'];
			$total[0]['contracts'] += $v['contracts'];
			$staffs[$v['id']]     = $v;
		}
		arsort($sort);
		$result=[];
		foreach ($sort as $id=>$v){
			$result[]=$staffs[$id];
		}
		$staffs=array_merge($total,$result);
		$this->success('请求成功',$staffs);
	}


    /**
     * 客户新增排行
     */
    public function newCustomer() {
        $date = input('date', date('Y-m'));
        $type = input('type', 0);

        if(strlen($date) == 4){
            $between = [strtotime($date . '-01-01'), strtotime($date.'-1-1 +1 year') - 1];
        }else{
            $between = [strtotime($date), strtotime('+1 month', strtotime($date)) - 1];
        }
        if ($type == 1) {//本人
            $ids = [$this->auth->id];
        } elseif ($type == 2) {//下属
            $ids = Staff::getLowerStaffId();
        } else {//全部
            $ids = Staff::getMyStaffIds();
        }
        $c         = Customer::where([
            'createtime'      => [
                'between',
                $between
            ],
            'owner_staff_id' => ['in', $ids]
        ])->group('owner_staff_id')->order('count desc')->field("owner_staff_id,count(*) as count")->select();
        $customers = [];
        foreach ($c as $v) {
            $customers[$v['owner_staff_id']] = $v['count'];
        }

        arsort($customers);
        $staffs    = Staff::getKeyList();
        $result    = [];
        $i         = 1;
        $data=[];
        foreach ($customers as $id => $number) {
            $val           = $staffs[$id];
            $val['number'] = $number;
            $val['rank']   = $i;
            $data[]=[
                'name'=>$val['name'],
                'number'=>$number
            ];
            $i++;
            $result[]     = $val;
        }

        $this->success('请求成功',['ranking' => $result, 'data' => $data]);
    }

    /**
     * 客户跟进排行
     */
    public function newRecord() {
        $date = input('date', date('Y-m'));
        $type = input('type', 0);

        if(strlen($date) == 4){
            $between = [strtotime($date . '-01-01'), strtotime($date.'-1-1 +1 year') - 1];
        }else{
            $between = [strtotime($date), strtotime('+1 month', strtotime($date)) - 1];
        }
        if ($type == 1) {//本人
            $ids = [$this->auth->id];
        } elseif ($type == 2) {//下属
            $ids = Staff::getLowerStaffId();
        } else {//全部
            $ids = Staff::getMyStaffIds();
        }
        //跟进次数
        $r= Record::where([
            'create_staff_id' => ['in',$ids],
            'relation_type' =>1,
            'createtime' => [
                'between',
                $between
            ]
        ])->field("create_staff_id,count(*) as count")->group('create_staff_id')->select();

        $records = [];
        foreach ($r as $v) {
            $records[$v['create_staff_id']] = $v['count'];
        }

        arsort($records);
        $staffs    = Staff::getKeyList();
        $result    = [];
        $data    = [];
        $i         = 1;
        foreach ($records as $id => $number) {
            $val           = $staffs[$id];
            $val['number'] = $number;
            $val['rank']   = $i;
            $data[]=[
                'name'=>$val['name'],
                'number'=>$number
            ];
            $i++;
            $result[]     = $val;
        }

        $this->success('请求成功',['ranking' => $result, 'data' => $data]);
    }

    /**
     * 获取业绩详情
     */
    public function getAchievementDetail()
    {
        $year = input('year', date('Y'));
        $status = input('status', 1);
        $staff_id = input('staff_id', '');
        if (empty($staff_id)) {
            $this->error('员工不能为空');
        }

        $ids = $staff_id;

        $achievements = AchievementModel::where(['type' => 3, 'obj_id' => ['in', $ids], 'year' => $year, 'status' => $status])
            ->field('sum(january) as january,sum(february) as february,sum(march) as march,sum(april) as april,sum(may) as may,sum(june) as june,sum(july) as july,sum(august) as august,sum(september) as september,sum(october) as october,sum(november) as november,sum(december) as december,sum(yeartarget) as yeartarget')->find()->toArray();
        if ($status == 1) {//合同金额
            $contracts = ContractRatio::where([
                'contract.check_status' => 2, 'contract_ratio.staff_id' => ['in', $ids],
                'contract.order_date' => ['like', $year . '%']
            ])->with(['contract'])->select();
            $contracts = collection($contracts)->toArray();
            $contractData = [];
            foreach ($contracts as $v) {
                $order_date = $v['contract']['order_date'];
                $month = date('Y-m', strtotime($order_date));
                $contractData[$month]['money'][] = $v['ratio_money'];
                $contractData[$month]['contract_id'][] = $v['contract_id'];
            }

            $list = [];
            foreach ($contractData as $month => $v) {
                $list[$month] = ['money' => array_sum($v['money']), 'count' => count($v['contract_id'])];
            }
        } else {
            $receivables = Receivables::where([
                'owner_staff_id' => ['in', $ids],
                'check_status' => 2,
                'return_time' => ['like', $year . '%'],
            ])->group('month')
                ->field('sum(money) as money,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as month,count(*) as count')->select();
            $list = [];
            foreach ($receivables as $v) {
                $list[$v['month']] = $v;
            }
        }
        $data = [];
        $echartdata = [];
        foreach ($achievements as $k => $v) {
            if ($month = AchievementModel::getFieldMonth($k)) {
                $month = $year . '-' . $month;
                $row = [
                    'month' => $month,
                    'achievement' => $v ?? 0,
                    'money' => isset($list[$month]) ? $list[$month]['money'] : 0,
                    'count' => isset($list[$month]) ? $list[$month]['count'] : 0,
                ];
                $row['ratio'] = ($row['money'] && intval($row['achievement'])) ? sprintf("%.2f", $row['money'] / $row['achievement'] * 100) : 0;
                $row['unit_price'] = ($row['money'] && $row['count']) ? sprintf("%.2f", $row['money'] / $row['count']) : 0;

                $echartdata['month'][] = $row['month'];
                $echartdata['achievement'][] = $row['achievement']??0;
                $echartdata['money'][] = $row['money'];
                $data[] = $row;
            }
        }
        $money = isset($echartdata['money']) ? array_sum($echartdata['money']) : 0;
        $ratio = ($money && intval($achievements['yeartarget'])) ? sprintf("%.2f", $money / $achievements['yeartarget'] * 100) : 0;
        $yeartarget = [
            'year' => $year,
            'money' => $money,
            'achievement' => $achievements['yeartarget'] ?? 0,
            'ratio' => $ratio
        ];
        $this->success('请求成功', ['data' => $data, 'echartdata' => $echartdata, 'yeartarget' => $yeartarget]);
    }

    /**
     * 排序
     * @param $data
     * @param $field
     * @param int $sort
     * @return mixed
     */
    public function arraySortByOneField($data, $field, $sort = SORT_ASC)
    {
        $field = array_column($data, $field);
        array_multisort($field, $sort, $data);
        return $data;
    }
}
